package ca.seia.comp6521.a1.memory;

import ca.seia.comp6521.a1.externalmergesort.ExternalMergeSortExecutionController;

public abstract class MemoryBuffer {

	protected int[] buffer;
	protected String assignedSublistFile;
	protected int capacity;
	protected int id;
	public int pointer;
	
	public MemoryBuffer(int capacity)
	{	
		this.pointer = 0;
		this.capacity = capacity;
		this.buffer = new int[this.capacity];
	}
	
	public MemoryBuffer(int capacity, int id) {
		this.capacity = capacity;
		this.buffer = new int[this.capacity];
		this.id = id;
		this.pointer = 0;
	}

	public MemoryBuffer(String assignedSublistFile, int capacity) {
		this.assignedSublistFile = assignedSublistFile;
		this.capacity = capacity;
		this.buffer = new int[this.capacity];
		this.pointer = 0;
	}
	
	public String getAssignedSublistFile() {
		return assignedSublistFile;
	}
	
	public int getCapacity() {
		return capacity;
	}
	public void setCapacity(int capacity) {
		this.capacity = capacity;
	}
	
	public void Insert(int i) throws FullBufferException {
		
		if(this.pointer < capacity)
		{
			this.buffer[pointer] = i;
			pointer ++;
		}
		else{
			throw new FullBufferException();
		}
		
	}
	
	public boolean isBufferFull() {
		return (this.buffer != null) ? pointer == capacity  : false;
	}
	
	
	public int getSize()
	{
		return pointer;
	}
	
	public int peek(){
		return this.buffer[pointer];
	}
	
	public int poll() {
		int value = this.buffer[pointer];
		this.buffer[pointer] = ExternalMergeSortExecutionController.UNUSED_NUMBER;
		pointer++;
		return value;
	}
	
	public void clear(){
		this.pointer = 0 ;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		MemoryBuffer other = (MemoryBuffer) obj;
		if (id != other.id)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "id=" + id + " MemoryBuffer [buffer=" + buffer + ", assignedSublistFile=" + assignedSublistFile + ", capacity=" + capacity + "]";
	}
	
	
	
	
}
